<!--
  * @Author: 黑白灰01 3193273703@qq.com
  * @Date: 2025-02-03 23:05:27
 * @LastEditors: 黑白灰01 3193273703@qq.com
 * @LastEditTime: 2025-02-08 16:44:18
  * @FilePath: /hei_picture_web/src/page/user/userInfoIndex.vue
  * @Description: 用户信息页面
  -->
<template>
  <div id="userInfoPage">
    <a-card :loading="loading">
      <!-- <pre>{{ userInfoData }}</pre> -->
      <userInfoCard class="infoCard" :userInfoData="userInfoData" />
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { getUserVoByIdUsingGet } from '@/api/userController'
import { ref, onMounted, watch } from 'vue'
import userInfoCard from './modal/userInfoCard.vue'
const loginUserStore = useLoginUserStore()
const userInfoData = ref<API.UserVO>() // 明确指定类型
const userId = ref<string | undefined>(undefined)
const loading = ref(false)
const isLoaded = ref(false) // 标记数据是否已加载

/**
 * 获取用户数据
 */
const fetchData = async () => {
  if (!userId.value) {
    console.log('用户 ID 不存在，无法发起请求')
    return
  }

  loading.value = true
  try {
    const { data: res } = await getUserVoByIdUsingGet({ id: userId.value })
    // console.log(res)
    if (res.code === 200) {
      userInfoData.value = res.data
      isLoaded.value = true // 数据加载成功，标记为已加载
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
  } finally {
    loading.value = false
  }
}

watch(
  () => loginUserStore.loginUserInfo.userId,
  async (newUserId) => {
    if (newUserId && newUserId !== userId.value && !isLoaded.value) {
      userId.value = newUserId
      await fetchData()
    }
  },
  { immediate: true }, // 初次加载时也会调用
)

onMounted(() => {
  if (loginUserStore.loginUserInfo.userId && !isLoaded.value) {
    userId.value = loginUserStore.loginUserInfo.userId
    fetchData()
  }
})
</script>

<style scoped>
.userInfoPage {
  max-width: 1000px;
  height: 100%;
  margin: 0 auto;
  .infoCard {
    width: 100%;
    height: 100%;
  }
}
</style>
